package geowiki.data;

import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;
import processing.xml.XMLElement;

/**
 * This extracts Links via YQL / xpath.
 */
public class YQLLinkExtractor extends LinkExtractor {

	public YQLLinkExtractor(PApplet p) {
		super(p);
	}

	public List<Link> getLinks(String input) {
		List<Link> links = new ArrayList<Link>();

		XMLElement xmlResponse = new XMLElement(p, input);
               // System.out.println(xmlResponse);
		XMLElement[] linkXMLElements = xmlResponse.getChildren("results/a");
		for (int i = 0; i < linkXMLElements.length; i++) {
			String title = linkXMLElements[i].getContent();
			String url = linkXMLElements[i].getStringAttribute("href");

			Link link = new Link(title, url, p);

			links.add(link);

		}

		return links;
	}

	public String getContent(String wikipediaURL) {
		String yqlQuery = YQLQuery.getMainContentDivFromWikiArticle(wikipediaURL);

		StringBuffer content = new StringBuffer();

		XMLElement xmlResponse = new XMLElement(p, yqlQuery);
		XMLElement[] contentXMLElements = xmlResponse.getChildren("results/div");
		for (int i = 0; i < contentXMLElements.length; i++) {
			content.append(contentXMLElements[i].toString());
		}
		if (contentXMLElements.length > 1) {
			PApplet.println("Warning: More than 1 found contents.");
		}

		return content.toString();
	}
	
	public String[] getMainParagraphs(String wikipediaURL) {


                String yqlQuery = YQLQuery.getParagraphsFromWikiArticle(wikipediaURL);

		XMLElement xmlResponse = new XMLElement(p, yqlQuery);
		XMLElement[] contentXMLElements = xmlResponse.getChildren("results/p");

		String[] paragraphs = new String[contentXMLElements.length];
		
		for (int i = 0; i < contentXMLElements.length; i++) {
			paragraphs[i] = contentXMLElements[i].toString();
		}

		return paragraphs;
	}
}
